package com.leonzx.base.service.system;

import com.leonzx.base.dao.system.UserRoleDAO;
import com.leonzx.base.entity.system.UserRole;
import com.leonzx.base.service.BaseService;
import com.leonzx.base.utils.Constants;
import com.leonzx.base.utils.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author:张勇
 * @Description:
 * @Date: 2018-06-17 13:47
 */
@Service
public class UserRoleService extends BaseService {
    @Autowired
    private UserRoleDAO userRoleDAO;

    /**
     * 人员关联角色时新建或者更新状态变为已关联，
     *
     * @param userRole
     */
    public void saveOrUpdate(UserRole userRole) {
        Example example = new Example(UserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userRole.getUserId());
        criteria.andEqualTo("roleId", userRole.getRoleId());
        UserRole userRole1 = userRoleDAO.selectOneByExample(example);
        if (Objects.isNull(userRole1)) {
            userRole.setId(UUIDUtils.getUUID());
            userRole.setCreateTime(new Date());
            userRoleDAO.insert(userRole);
        } else {
            userRole.setCreateTime(new Date());
            userRoleDAO.updateByExampleSelective(userRole, example);
        }
    }

    /**
     * 根据条件查找所又UserRole
     *
     * @param userRole
     * @return
     */
    public List<UserRole> findByUserIdAndRoleIdAndState(UserRole userRole) {
        Example example = new Example(UserRole.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(userRole.getUserId())) {
            criteria.andEqualTo("userId", userRole.getUserId());
        }
        if (!Objects.isNull(userRole.getState())) {
            criteria.andEqualTo("state", userRole.getState());
        }
        if (StringUtils.isNotBlank(userRole.getRoleId())) {
            criteria.andEqualTo("roleId", userRole.getRoleId());
        }
        return userRoleDAO.selectByExample(example);
    }

    public String findRoleStrByUserId(String userId) {
        String str = "";
        List<String> roles = userRoleDAO.findRoleIdByUserId(userId, Constants.STATE_VAILD);
        if (roles != null && roles.size() > 0) {
            for (int i = 0; i < roles.size(); i++) {
                str += roles.get(i) + ",";
            }
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

}
